package interview.java.q1.internal.secret;

public class OneCircleFiller {

  public OneCircleFiller(int[][] result, int start, int circle) {
    _result = result;
    _start = start;
    _circle = circle;
  }

  public int fill() {
    int cursor = _start;
    int dir = 0;

    int row = _circle;
    int col = _circle;

    while (_result[row][col] == 0) {
//      System.out.println(row + "," + col + "->" + _result[row][col]);
      _result[row][col] = cursor;
      cursor++;

      int nextRow = row + DIR[dir][0];
      int nextCol = col + DIR[dir][1];

//      System.out.println("next: " + nextRow + "," + nextCol);
      if (nextRow >= _result.length || nextCol >= _result[row].length ||
          nextRow < 0 || nextCol < 0 || _result[nextRow][nextCol] > 0) {
        dir++;

        if (dir >= DIR.length) {
          return cursor;
        }

        nextRow = row + DIR[dir][0];
        nextCol = col + DIR[dir][1];
      }

//      System.out.println(row + "," + col);
      row = nextRow;
      col = nextCol;
    }

    return cursor;
  }

  private static final int[][] DIR = {
      {+1, 0},
      {0, +1},
      {-1, 0},
      {0, -1},
  };

  private final int[][] _result;

  private final int _start;
  private final int _circle;
}
